package com.zs.grain.tool;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;

import com.zs.grain.R;
import com.xnkj1688.semplibrary.dialog.DialogResult;

public class YesNoDialog extends Dialog implements View.OnClickListener{

    DialogResult dialogResult;
    Handler mHandler;
    public YesNoDialog(Context context) {
        super(context);
    }
    public YesNoDialog(Context context, int theme) {
        super(context, theme);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.dialog_yes_no);
        initArguments();
        initViews();
    }
    private void initArguments() {
    }
    private void initViews() {
        findViewById(R.id.yesButton).setOnClickListener(this);
        findViewById(R.id.noButton).setOnClickListener(this);
    }

    @Override
    protected void onStart() {

    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.yesButton) {
            endDialog(DialogResult.OK);
        } else if (i == R.id.noButton) {
            endDialog(DialogResult.CANCEL);
        }
    }

    public void setDialogResult(DialogResult dialogResult) {
        this.dialogResult = dialogResult;
    }

    public synchronized void endDialog(DialogResult result) {
        if (mHandler != null) {
            setDialogResult(result);
            Message m = mHandler.obtainMessage();
            mHandler.sendMessage(m);
            mHandler = null;
        }
        dismiss();
    }

    public DialogResult showDialog() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message mesg) {
                // process incoming messages here
                //super.handleMessage(msg);
                throw new RuntimeException("endDialog");
            }
        };
        this.setCancelable(false);
        super.show();
        try {
            Looper.getMainLooper().loop();
        } catch (RuntimeException e) {
            mHandler = null;
//            if (!"endDialog".equals(e.getMessage()))
//                throw e;
        }
        return dialogResult;
    }
}
